<?php
namespace app\common\command;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use app\common\model\StudentAttence;
use app\common\model\SchoolEnroll;

/**
 * 根据考勤自动销课
 */
class Autochipcourse extends Command
{
    protected function configure()
    {
        $this->setName('autochipcourse')
            ->setDescription('根据考勤自动销课');
    }

    protected function execute(Input $input, Output $output)
    {
        $attence = StudentAttence::alias('m')
        ->field('m.id,m.stu_id,m.school_id,m.class_id,m.course_id,m.create_time as attence_time,m.face_img,stu.full_name as stu_fullname,up.uid as parent_uid,up.full_name as parent_fullname,sch.school_name')
        ->join('__STUDENT_INFO__ stu','m.stu_id=stu.id' , 'left')
        ->join('__USER__ up','stu.parent_uid=up.uid' , 'left')
        ->join('__SCHOOL__ sch','m.school_id=sch.id' , 'left')
        ->where('m.status',1)->find();
        if ( empty($attence) ) return $output->writeln('1执行成功,无数据。时间：'  . date('Y-m-d H:i:s'));

        $attence = $attence->toArray();

        $output->writeln(json_encode($attence));

        ## 自动销课 - 只对按次（课时）的课程有效
        $enroll = SchoolEnroll::where(['register_type','IN', '1,2'])->where('stu_id',$attence['stu_id'])->where('course_id',$attence['course_id'])->where('school_id',$attence['school_id'])->find();
        if ( !empty($enroll) ) {
            $enroll = $enroll->toArray();

            $enroll_update = [];

            ## 无论销课类型是哪一种，只要超出最大期限，一样将状态设为2
            if ( strtotime($enroll['course_end']) < time()  ) {
                $enroll_update['status'] = 2;
            }

            if ( $enroll['nums_unit'] == 'TIMES' ) {
                if ( $enroll['left_nums'] == 1 ) {
                    $enroll_update['status'] = 2;
                }
                $enroll_update['left_nums'] = $enroll['left_nums'] - 1;
            }

            if (!empty($enroll_update) ) {
                $res = SchoolEnroll::where('id' , $enroll['id'])->update($enroll_update);
                if ( $res === false ) $output->writeln('执行失败,销课失败。时间：'  . date('Y-m-d H:i:s'));
            }
        }

        ## 发送通知
        $res = StudentAttence::sendMessage($attence);
        $output->writeln($res);

        ## 状态设为2，后续不再处理
        StudentAttence::where('id',$attence['id'])->update(['status' => 2]);

        $output->writeln('执行成功,时间：'  . date('Y-m-d H:i:s'));
        return true;
    }
}// Class End